package com.woniu.jobhandler;


import com.woniu.config.DingTalkService;
import com.woniu.entity.OrderDailyReport;
import com.woniu.mapper.OrderDailyReportMapper;
import com.woniu.mapper.OrderMapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Component
public class OrderReportJobHandler {

    @Autowired
    private OrderMapper orderMapper;

    @Resource
    private OrderDailyReportMapper reportMapper;

    @Resource
    private DingTalkService dingTalkService;

    @Resource
    private RestTemplate restTemplate; // 确保容器中有 RestTemplate


    @XxlJob("dailyOrderReportJob")
    public void generateDailyReport() throws Exception {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        XxlJobHelper.log("开始生成 {} 的订单日报", yesterday);

        try {
            // 查询昨日数据
            int orderCount = orderMapper.countByDate(yesterday);
            BigDecimal totalAmount = orderMapper.sumAmountByDate(yesterday);
            BigDecimal refundAmount = orderMapper.sumRefundByDate(yesterday);
            int newUserOrders = orderMapper.countNewUserOrders(yesterday);

            // 构建报表对象
            OrderDailyReport report = new OrderDailyReport();
            report.setReportDate(java.sql.Date.valueOf(yesterday));
            report.setOrderCount(orderCount);
            report.setTotalAmount(totalAmount != null ? totalAmount : BigDecimal.ZERO);
            report.setRefundAmount(refundAmount != null ? refundAmount : BigDecimal.ZERO);
            report.setNewUserOrders(newUserOrders);
            report.setCreatedTime(new Date());
            report.setUpdatedTime(new Date());

            // 保存或更新（upsert）
            int rows = reportMapper.upsert(report);
            if (rows > 0) {
                XxlJobHelper.log("成功生成日报：订单数={}, 销售额={}", orderCount, report.getTotalAmount());
            } else {
                XxlJobHelper.log("日报生成但未影响记录，请检查主键是否正确匹配");
            }

            // ✅ 发送钉钉通知（Markdown 更好看）
            String markdownMsg = String.format(
                    "### 📊 昨日订单报表（%s）\n\n" +
                            "- **订单总量**：%d 单\n" +
                            "- **总销售额**：￥ %s\n" +
                            "- **退款金额**：￥ %s\n" +
                            "- **新客订单**：%d 单\n\n" +
                            "---\n" +
                            "⌚ 自动化报表系统 · %s",
                    yesterday,
                    orderCount,
                    report.getTotalAmount().toPlainString(),
                    report.getRefundAmount().toPlainString(),
                    newUserOrders,
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
            );

            dingTalkService.sendMarkdown("📊 昨日订单报表", markdownMsg);

        } catch (Exception e) {
            XxlJobHelper.log("生成日报异常: " + e.getMessage());
            throw e; // 抛出异常，XXL-JOB 会标记为失败并可能触发重试
        }
    }
}